iT邦幫忙

DAY 18
0

練習如何去開發一個通訊軟體 Boo it!系列 第 18

Day18 - 交換訊息中心 Boo it - chat_server 。

  • 分享至 

  • xImage
  •  

接下來我們就結合前面所介紹的,利用web-socket以及 EM-Machine來做我們的通訊軟體訊息交換中心

換句話說,就是幫助我們傳遞訊息的伺服器。

並且利用mongoDB來儲存歷史訊息。

以下是程式碼

require 'em-websocket'

require 'mongo'

require 'json'

include Mongo

#

# connecting to the database (for history)

#

client = MongoClient.new # defaults to localhost:27017

db     = client['Boo']

@coll  = db['dialog']

#

# boo_log history method

#

def boo_log(logStr)

    _currentTime = Time.new.to_s

    _logAry = logStr.split(',')

    _sortAry = [_logAry[0].to_s,_logAry[1].to_s].sort

    _did = _sortAry[0].to_s + _sortAry[1].to_s

    if @coll.find("did" => _did).to_a.empty?

        # if not found , then insert

        _jsonObj_insert = {:did => _did,:dialog => [{:from => _logAry[0] , :to => _logAry[1] , :datetime => _currentTime , :log => _logAry[2]}]}

        @coll.insert(_jsonObj_insert)

    else

       # if found , then update

       @coll.update({:did => _did}, {:$push => {:dialog => {:from => _logAry[0] , :to => _logAry[1] , :datetime => _currentTime , :log => _logAry[2]}}},:upsert => true)

    end

end

#

# chat server

#

puts "Server is listening!..."

@uid = []

@sid = []

@channel_list = []

EM.run {

    @channel = EM::Channel.new

  EM::WebSocket.run(:host => "0.0.0.0", :port => 8080) do |ws|

    ws.onopen { |handshake|

      puts "WebSocket connection open"

      # first message to subscribe channel

      @sid << @channel.subscribe {|msg|

          puts "received:" + msg + "---"

          ws.send msg # send itself

          puts "history record"

      }

      tid = @sid.last

      puts "#{@sid.last} connect!"

      ws.onmessage {|msg|

        @uid = msg.split(/,/)

        @channel.push "#{msg}"

        boo_log(msg.to_s)

      }

      ws.onclose {

          @channel.unsubscribe(tid)

          puts "#{tid} conection closed!"

      }

     

    }  # onopen end

  end

}

好的,可以看到都是用很簡單的章節範例去製成我們所需要的功能,那就稍微介紹一下各個部分在做什麼。

首先,我先必須先引用library

require 'em-websocket'

require 'mongo'

require 'json'

include Mongo

接下來就是設定存取mongoDB的歷史訊息

client = MongoClient.new # defaults to localhost:27017

db     = client['Boo']

@coll  = db['dialog']

定義存取歷史訊息的方法

def boo_log(logStr)

    _currentTime = Time.new.to_s

    _logAry = logStr.split(',')

    _sortAry = [_logAry[0].to_s,_logAry[1].to_s].sort

    _did = _sortAry[0].to_s + _sortAry[1].to_s

    if @coll.find("did" => _did).to_a.empty?

        # 如果沒有找到歷史紀錄,則插入訊息到資料庫

        _jsonObj_insert = {:did => _did,:dialog => [{:from => _logAry[0] , :to => _logAry[1] , :datetime => _currentTime , :log => _logAry[2]}]}

        @coll.insert(_jsonObj_insert)

    else

       # i如果有找到歷史訊息,就更新(append到下方)

       @coll.update({:did => _did}, {:$push => {:dialog => {:from => _logAry[0] , :to => _logAry[1] , :datetime => _currentTime , :log => _logAry[2]}}},:upsert => true)

    end

end

因為我們是利用廣播訊息來達到傳遞訊息的效果。(概念像是在聊天室中傳遞悄悄話所以我們可以透過以下程式來達到這個效果)

puts "Server is listening!..."

@uid = []

@sid = []

@channel_list = []

EM.run {

    @channel = EM::Channel.new

  EM::WebSocket.run(:host => "0.0.0.0", :port => 8080) do |ws|

    ws.onopen { |handshake|

      puts "WebSocket connection open"

      # first message to subscribe channel

      @sid << @channel.subscribe {|msg| #新進來的連線加入channel

          puts "received:" + msg + "---" #顯示收到的訊息

          ws.send msg # send itself #傳回去給CLIENT端

          puts "history record" # 歷史訊息紀錄

      }

      tid = @sid.last

      puts "#{@sid.last} connect!"

      ws.onmessage {|msg|

        @uid = msg.split(/,/)

        @channel.push "#{msg}"

        boo_log(msg.to_s)

      }

      ws.onclose {

          @channel.unsubscribe(tid)

          puts "#{tid} conection closed!"

      }

     

    }  # onopen end

  end

}

透過以上的程式碼。我們可以直接運行。利用前面章節WEB-SOCKET的Client端,就可以達到通訊的效果。

後面,我們會介紹如何去傳遞訊息以及設定參數、朋友名單以及特定對象傳訊。


上一篇
Day 17 – Sinatra 與MongoDB的約會!
下一篇
Day 19 Boo-it Au_server - 1 序曲。
系列文
練習如何去開發一個通訊軟體 Boo it!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言